<template>
  <el-form :model="form" :rules="rules">
    <el-form-item prop="username">
        <el-input v-model="form.username" placeholder="用户名">
         <template #prefix> <!-- 插槽必须放在el-input内部 -->
              <el-icon class="input-icon"><User /></el-icon>
         </template>
         </el-input>
    </el-form-item>
    
    <el-form-item prop="password">
        <el-input v-model="form.password" type="password" show-password placeholder="密码">
            <template #prefix>
                <el-icon class="input-icon"><Lock /></el-icon>
            </template>
        </el-input>
    </el-form-item>

    
    <el-button 
      type="primary" 
      class="floating-btn"
      @click="handleLogin"
    >
      立即登录
    </el-button>
  </el-form>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import axios from '@/utils/request'
// 在script setup顶部添加
import { User, Lock } from '@element-plus/icons-vue'
defineExpose({ User, Lock }) 

interface LoginForm {
  username: string
  password: string
}

const form = reactive<LoginForm>({
  username: '',
  password: ''
})

const rules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 12, message: '长度3-12字符' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/, 
      message: '需包含字母和数字' }
  ]
})

const router = useRouter()
const loading = ref(false)

const handleLogin = async () => {
  try {
    const { data } = await axios.post('/auth/login', form)
    localStorage.setItem('token', data.token)
    router.push('/dashboard')
  } catch (err) {
    console.error('登录失败', err)
  } finally {
    loading.value = false
  }
}
</script>
<style>
.input-icon {
  vertical-align: middle;
  margin-right: 8px;
  font-size: 16px;
  color: #666;  /* 防止白色背景中图标不可见 */
}
</style>